package com.gzz.orchid.common.webmvc.converter.enums;

import com.gzz.orchid.common.core.support.IBaseEnum;
import org.springframework.core.convert.converter.Converter;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 枚举编码 -> 枚举 转化器
 *
 * @author higmd
 */
public class IntegerToEnumConverter<T extends IBaseEnum> implements Converter<Integer, T> {
    private final Map<Integer, T> enumMap = new HashMap<Integer, T>();

    public IntegerToEnumConverter(Class<T> enumType) {
        T[] enums = enumType.getEnumConstants();
        for (T e : enums) {
            enumMap.put(e.getValue(), e);
        }
    }

    @Override
    public T convert(Integer source) {
        T t = enumMap.get(source);
        if (Objects.isNull(t)) {
            throw new IllegalArgumentException("无法匹配对应的枚举类型");
        }
        return t;
    }
}